import React,{Component} from 'react'
import moment from 'moment';
import ReactDOM from 'react-dom';
import {
    List,
    Card,
    Row,
    Col,
    Radio,
    Input,
    Progress,
    Button,
    Icon,
    Dropdown,
    Menu,
    Avatar,
    Modal,
    Form,
    DatePicker,
    Select,
    notification,
} from 'antd';
import styles from './Manage.less';
import Result from '@/components/Result';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {connect} from "react-redux";
import {FETCH_DEVICES, REFRESH_DEVICES} from "../../models/device/const";
import {createDevice, deleteDevice, updateDevice} from "../../services/device";
import {base_url, OFFLINE, ONLINE, RUNNING} from "../../config/const";
import MyDeviceTypeSelect from "../../components/MyDeviceTypeSelect";
import getDeviceList from "../../models/selectors";


const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

const {Option} = Select;
@connect(({ device}) => {
    return ({
        deviceList:getDeviceList(device)
    })
})
@Form.create()
class DeviceSetting extends Component {
    constructor(props) {
        super(props);
        this.state={
            visible: false,
            done: false,
            sort: 1,
            status: -1,
            current: null,
            online:0,
            offline:0,
            all_device:[]
        };
        const {dispatch}=this.props;
        dispatch({
            type:FETCH_DEVICES
        })
    }


    formLayout = {
        labelCol: {span: 7},
        wrapperCol: {span: 13},
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: REFRESH_DEVICES
        })
    }
    getDeviceID=async (type)=>{
        if(localStorage.getItem('user')){
            var  user=JSON.parse(localStorage.getItem('user')).username;
            var  company_id=JSON.parse(localStorage.getItem('user')).company_id;
        }
        const url=`${base_url}device_list/?user=${user}&company_id=${company_id}`;
        const response=await new Promise(resolve=>{
            fetch(url).then(res=>res.json()).then(res=>{
                resolve(res)
            })
        });
        var onCount=0,offCount=0;
        response.data.forEach((item,index)=>{
            if(item.status===0){
                onCount++;
            }else{
                offCount++;
            }
        });
        this.setState({
            all_device:response.data,
            online:onCount,
            offline:offCount
        })
    };
    handleClassChange=(e)=>{
        const status = parseFloat(e.target.value);
        this.setState({status})
    };
    handleSortChange = (e) => {
        const sort = e.target.value;
        this.setState({sort})
    };

    getData = (data) => {
        if (this.state.status === -1){
        }else if(this.state.status===0){
            data = data.filter(item => {
                if(item.status===0){
                    return item;
                }
            });
        }else {
            data = data.filter(item => {
                if(item.status===2){
                    return item;
                }
            });
        }
        return data;
        // return data.sort((a, b) => sort * (a.device_id - b.device_id))
    };

    showEditModal = item => {
        this.setState({
            visible: true,
            current: item,
        });
    };
    handleDone = () => {
        this.setState({
            done: false,
            visible: false,
        });
    };
    handleCancel = () => {
        this.setState({
            visible: false,
        });
    };
    handleSubmit = e => {
        e.preventDefault();
        const {form} = this.props;
        const {current} = this.state;
        const device_id = current ? current.device_id : '';

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            this.handleUpdateDevice(device_id, fieldsValue)
        });
    };
    
    handleUpdateDevice = async (device_id, fieldsValue) => {
        const rsp = await updateDevice(device_id, fieldsValue);
        if (rsp.statusCode === 201) {
            const {dispatch} = this.props;
            dispatch({
                type: REFRESH_DEVICES,
            });
            this.setState({
                done: true,
            });
        } else {
            this.setState({visible: false, done: false})
        }
    };
    
    render() {
        const {deviceList,form}=this.props;
        const { getFieldDecorator } = form;
        const {status,sort,current,visible,done}=this.state;
        if(deviceList){
            var  tableData=deviceList;
            var statusMap = tableData.reduce((obj, item) => (++obj[item.status], obj), {
                [ONLINE]: 0,
                [RUNNING]: 0,
                [OFFLINE]: 0,
            });
        }

        const editAndDelete = (key, currentItem) => {
            if (key === 'edit') this.showEditModal(currentItem);
            else if (key === 'delete') {
                Modal.confirm({
                    // title: '删除任务',
                    content: '确定删除该设备吗？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => this.deleteItem(currentItem.device_id),
                });
            }
        };

          const ListContent = ({
                                   data: {
                                      device_id,
                                      device_name
                                   }
                               }) => (
              <div className={styles.listContent}>
                  <div className={styles.listContentItem}>
                      <span>设备名称</span>
                      <p>{device_name}</p>
                  </div>
              </div>
          );
        /**
         * 排序：过滤
         */
        const getData = (data) => {
            if (status !== -1) data = data.filter(item => item.status === status);
            return data.sort((a, b) => sort * (parseInt(a.device_id) - parseInt(b.device_id)));
        };

        const modalFooter = done
            ? {footer: null, onCancel: this.handleDone}
            : {okText: '保存', onOk: current ? this.handleSubmit : this.handleAddDevice, onCancel: this.handleCancel};


        const getModalContent = (current) => {
            if (done) {
                return (
                    <Result
                        type="success"
                        title="操作成功"
                        // description="一系列的信息描述，很短同样也可以带标点。"
                        actions={
                            <Button type="primary" onClick={this.handleDone}>
                                知道了
                            </Button>
                        }
                        className={styles.formResult}
                    />
                );
            }
            if (current) return (
                <Form onSubmit={this.handleSubmit}>
                    <FormItem label="设备名称" {...this.formLayout}>
                        {getFieldDecorator('device_name', {
                            rules: [{required: true, message: '请输入设备名称'}],
                            initialValue: current.device_name,
                        })(<Input placeholder="请输入"/>)}
                    </FormItem>
                </Form>
            );

            return (
                <Form >
                    aaa
                    {/*<FormItem label="设备编号" {...this.formLayout}>*/}
                    {/*    {getFieldDecorator('id', {*/}
                    {/*        rules: [{required: true, message: '请输入设备编号'}],*/}
                    {/*    })(<Input placeholder="请输入"/>)}*/}
                    {/*</FormItem>*/}
                    {/*<FormItem label="设备名称" {...this.formLayout}>*/}
                    {/*    {getFieldDecorator('nickname', {})(<Input placeholder="请输入"/>)}*/}
                    {/*</FormItem>*/}
                    {/*<FormItem label="设备描述" {...this.formLayout}>*/}
                    {/*    {getFieldDecorator('desc', {})(<Input placeholder="请输入"/>)}*/}
                    {/*</FormItem>*/}
                    {/*<FormItem label="设备分类" {...this.formLayout}>*/}
                    {/*    {getFieldDecorator('type', {*/}
                    {/*        initialValue: '0',*/}
                    {/*        rules: [{required: true, message: '请选择设备分类'}],*/}
                    {/*    })(<Select>*/}
                    {/*        <Option value="0">一期</Option>*/}
                    {/*        <Option value="1">二期</Option>*/}
                    {/*    </Select>)}*/}
                    {/*</FormItem>*/}
                </Form>
            )
        };
        return (
            <PageHeaderWrapper>
                {
                    deviceList? ( <div className={styles.standardList}>
                        <Card
                            className={styles.listCard}
                            bordered={false}
                            title={<div>
                                设备管理
                                <MyDeviceTypeSelect/>
                            </div>}
                            style={{marginTop: 24}}
                            bodyStyle={{padding: '0 32px 40px 32px'}}
                            // extra={<Button onClick={this.showModal} type="primary" shape="circle" icon="plus"/>}//增加
                        >
                            <div style={{float: 'left'}}>
                                状态:
                                <RadioGroup defaultValue="-1" onChange={this.handleClassChange}>
                                    <RadioButton value='-1'>全部</RadioButton>
                                    <RadioButton value={RUNNING}>在线{statusMap[RUNNING]} </RadioButton>
                                    <RadioButton value={OFFLINE}>离线{statusMap[OFFLINE]} </RadioButton>
                                </RadioGroup>
                            </div>

                            <div style={{float: 'right'}}>
                                <Radio.Group defaultValue="1" onChange={this.handleSortChange}>
                                    <Radio.Button value="1"><Icon type="up"/> 升序排列</Radio.Button>
                                    <Radio.Button value="-1">降序排列 <Icon type="down"/></Radio.Button>
                                </Radio.Group>
                            </div>
                            <div style={{clear: 'both', margin: '40px 0'}}/>
                            <List
                                size="large"
                                rowKey="id"
                                loading={false}
                                pagination={true}
                                // dataSource={this.getData(this.state.all_device)}
                                dataSource={getData(tableData)}
                                renderItem={item => (
                                    <List.Item
                                        actions={[
                                            <a
                                                onClick={e => {
                                                    e.preventDefault();
                                                    editAndDelete('edit', item);
                                                }}
                                            >编辑
                                            </a>,
                                            <a onClick={e => {
                                                e.preventDefault();
                                                editAndDelete('delete', item);
                                            }} style={{'display':'none'}}>删除</a>
                                            ,
                                        ]}
                                    >
                                        <List.Item.Meta
                                            title={<span>设备编号: {item.device_id}</span>}
                                        />
                                        <ListContent data={item}/>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </div>):null
                }

                <Modal
                    title={done ? null : `设备${current ? '编辑' : '添加'}`}
                    // className={styles.standardListForm}
                    width={640}
                    bodyStyle={done ? {padding: '72px 0'} : {padding: '28px 0 0'}}
                    destroyOnClose
                    visible={visible}
                    {...modalFooter}
                >
                    {getModalContent(current)}
                </Modal>
            </PageHeaderWrapper>
        );
    }
}

export default DeviceSetting;
